package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.pojo.dto.PlayBackSwitchGetDTO;
import com.xbongbong.paas.pojo.dto.PlayBackSwitchSetDTO;
import com.xbongbong.paas.pojo.vo.PlayBackSwitchVO;
import com.xbongbong.paas.service.PlayBackSwitchService;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * 流量回放开关控制
 * @author 李少杰
 * @version v1.0.0
 * @date 2020/11/24 9:15
 * @since v1.0.0
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/playBack/switchStatus")
public class PlayBackController {

    @Resource
    private PlayBackSwitchService playBackSwitchService;

    /**
     * 设置流量回放的开关的白名单
     * @param playBackSwitchSetDTO dto
     * @param br br
     * @return xbbResponse
     */
    @RequestMapping(value = "/set", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String set(@RequestBody @Valid PlayBackSwitchSetDTO playBackSwitchSetDTO, BindingResult br) {
        XbbResponse<PlayBackSwitchVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            PlayBackSwitchVO playBackSwitchVO = playBackSwitchService.setSwitchStatus(playBackSwitchSetDTO);
            response = new XbbResponse<>(playBackSwitchVO);
        }
        return JSON.toJSONString(response);
    }

    /**
     * 获取流量回放开关的状态
     * @param playBackSwitchGetDTO dto
     * @param br br
     * @return xbbResponse
     */
    @RequestMapping(value = "/get", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String get(@RequestBody @Valid PlayBackSwitchGetDTO playBackSwitchGetDTO, BindingResult br) {
        XbbResponse<PlayBackSwitchVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            PlayBackSwitchVO playBackSwitchVO = playBackSwitchService.getSwitchStatus(playBackSwitchGetDTO);
            response = new XbbResponse<>(playBackSwitchVO);
        }
        return JSON.toJSONString(response);
    }

}
